$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_gctzch_m")
    let dgrid1 = $NG.getCmpApi("p_form_gctzch_d2")
    let dgrid2 = $NG.getCmpApi("p_form_gctzch_d3")
    const getHeadValue = (str) => mstform.getItem(str).getValue()

    const param = parseUrlParams(location.href)

    const config = {
        saveLock: false
    }

    if (param.sourceid && !mstform.getItem("u_lyid").getValue()) {
        mstform.getItem("u_lyid").setValue(param.sourceid)
    }
    selectTabs('1')
    isTabs()

    const saves = ['save', 'check']

    saves.forEach(item => {
        useBeforeClick(() => {
            if (config.saveLock) {
                $NG.alert("当前项目策划已经含有收尾策划，不可新增！")
                return false
            }
        }, item)
    })


    useValuesChange(() => {
        // selectTabs('1')
        isTabs()
        hiddenAttmentch()
    }, "p_form_gctzch_m.u_chzt")

    useValuesChange(() => {
        getXmchByPhid()
        getVersion()
        getSwFrom()

    }, "p_form_gctzch_m.u_chmc")

    useUpdateRow(() => {
        sumAmt()
    }, "p_form_gctzch_d2")

    useUpdateRows(({ args }) => {
        return // 目前发现他好像没什么用了，临时停止，后期没问题可删除
        const rows = dgrid1.getRows()
        let u_qrdyysr = 0
        let u_gcjsje = 0
        let u_gsglf = 0
        let u_fgsglf = 0
        let u_lrze = 0
        let u_lrl = 0
        rows.forEach(el => {
            el.s_tree_name = el.s_tree_name.replaceAll(" ", "")
            console.log(el.s_tree_name, el.s_tree_name == '公司');
            if (el.s_tree_name.includes("营业收入")) {
                u_qrdyysr += (Number(el.u_je) || 0)
            }
            if (el.s_tree_name.includes("工程结算金额")) {
                u_gcjsje += (Number(el.u_je) || 0)
            }
            if (el.s_tree_name == '公司') {
                console.log(`设置公司`,);
                u_gsglf += (Number(el.u_je) || 0)
            }
            if (el.s_tree_name == '分公司') {
                u_fgsglf += (Number(el.u_je) || 0)
            }
            if (el.s_tree_name == '利润总额') {
                u_lrze += (Number(el.u_je) || 0)
            }
            if (el.s_tree_name.includes('利润率')) {
                u_lrl += (Number(el.u_je) || 0)
            }
        })
        mstform.getItem("u_qrdyysr").setValue(u_qrdyysr)
        mstform.getItem("u_gcjsje").setValue(u_gcjsje)
        mstform.getItem("u_gsglf").setValue(u_gsglf)
        mstform.getItem("u_fgsglf").setValue(u_fgsglf)
        mstform.getItem("u_lrze").setValue(u_lrze)
        mstform.getItem("u_lrl").setValue(u_lrl)
        dgrid1.refreshView()
    }, "p_form_gctzch_d2")

    function getXmchInfo() {
        dgrid1 = $NG.getCmpApi("p_form_gctzch_d2")
        dgrid2 = $NG.getCmpApi("p_form_gctzch_d3")
        const phid = getHeadValue("u_chmc")
        console.log(`测试`,phid);
        if (!phid) return
        if(page.oType !='add') return 
        $NG.execServer("SELECT", {
            sql: `select d.phid,d.u_cbbm,u_zysb, d.s_tree_id,
             d.s_tree_no, d.s_tree_name, d.s_tree_pid,d.u_bz, d.u_je from p_form_xmch_d1 d left join p_form_xmch_m m on m.phid = d.pphid where m.phid = '${phid}'`
        }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data).reduce((value, it) => {
                const item = it.extendObjects
                value.push({
                    ...item,
                    u_yychje: item.u_je,
                    u_zysb: item.u_zysb, 
                    u_bz: item.u_bz,
                    u_sourceid: item.phid
                })
                return value
            }, [])
            const arr = arrayToTree(datas, "s_tree_id", "s_tree_pid")
            console.log('添加的数据', arr)
            dgrid1.clearRows().then(() => {
                dgrid1.addRows(arr)
            })
        })
    }

    function sumAmt() {
        const rows = dgrid1.getRows()
        const new_row = flattenTreeAndDeduplicate(rows)// 汇总前计算
        new_row.forEach(el => {
            el.u_syje = (Number(el.u_yychje) || 0) - (Number(el.u_ywgje) || 0)
            el.u_bghchje = (Number(el.u_yychje) || 0) + (Number(el.u_bgzjje) || 0)
        })
        childReduceTree(rows)
        let u_hte = 0
        let u_yysrbhbyj = 0
        let u_zcb = 0
        let u_fgsglf = 0
        let u_gsglf = 0
        let u_qrdyysr = 0 // TODO
        let u_zcb1 = 0
        let u_lrl = 0
        let u_lrze = 0
        let u_lr = 0
        let u_lrl_ = 0
        new_row.forEach(item => {
            const tree_name = item.s_tree_name.replaceAll(" ", "").replaceAll("\n", "").replaceAll("\\n", "")
            if (tree_name == '合同金额') {
                u_hte = (Number(item.u_bgzjje) || 0)
            } else if (tree_name == '预计营业收入') {
                u_yysrbhbyj = (Number(item.u_bgzjje) || 0)
                u_qrdyysr = (Number(item.u_ywgje) || 0)
            } else if (tree_name == '分公司管理费率') {
                u_fgsglf = (Number(item.u_ywgje) || 0)
            } else if (tree_name == '公司管理费率') {
                u_gsglf = (Number(item.u_ywgje) || 0)
            }else if (tree_name == '成本') {
                console.log(`ittem`,item,item.u_bgzjje);
                u_zcb = (Number(item.u_bgzjje) || 0)
                u_zcb1 = (Number(item.u_ywgje) || 0)
            } 
        })
        u_lrze = u_qrdyysr - u_zcb1
        u_lrl = u_qrdyysr?(u_lrze / u_qrdyysr):0
        u_lr = u_yysrbhbyj - u_zcb
        u_lrl_ =u_yysrbhbyj? u_lr / u_yysrbhbyj:0
        mstform.getItem("u_hte").setValue(u_hte)
        mstform.getItem("u_yysrbhbyj").setValue(u_yysrbhbyj)
        mstform.getItem("u_zcb").setValue(u_zcb)
        mstform.getItem("u_fgsglf").setValue(u_fgsglf)
        mstform.getItem("u_gsglf").setValue(u_gsglf)
        mstform.getItem("u_qrdyysr").setValue(u_qrdyysr)
        mstform.getItem("u_zcb1").setValue(u_zcb1)
        mstform.getItem("u_lrl").setValue(u_lrl)
        mstform.getItem("u_lrze").setValue(u_lrze)
        mstform.getItem("u_lr").setValue(u_lr)
        mstform.getItem("u_lrl_").setValue(u_lrl_)
        dgrid1.refreshView()
    }


    function isTabs() {
        const bo = mstform.getItem("u_chzt").getValue()
        console.log(`策划状态`,bo);
        if (bo == '01') {
            selectTabs("tabPanel_tabItem,tabPanel_tabItem_1")
        } else {
            selectTabs('1')
        }
        setTimeout(() => {
            dgrid1 = $NG.getCmpApi("p_form_gctzch_d2")
            dgrid2 = $NG.getCmpApi("p_form_gctzch_d3")
        }, 200)

    }
    // 进场策划调整
    function selectTabs(key) {
        const u_chzt = getHeadValue("u_chzt")
        const tabs = $NG
            .getCompMap()
            .get("__Tabs__")[0]
            .getApi();

        tabs.updateItems((innerItems, activeKey) => {
            return [...innerItems.filter((item) => {
                if (key.split(",").includes(item.name) && item.name != "tabPanel_tabItem_1") {
                    return item
                }
            })];
        });
        setTimeout(() => {
            if (key != '1') {
                getXmchInfo()
            }
        }, 500)
    }

    // 获取项目策划信息
    function getXmchByPhid() {
        const phid = getHeadValue("u_chmc")
        if (!phid) return
        $NG.execServer("getXmchByPhid", { phid }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            const arr = [
                {
                    key: "u_xmmc",
                    value: {
                        label: datas.u_xmmc_exname,
                        value: datas.phid_pc
                    }
                },
                {
                    key: "u_htmc",
                    value: {
                        label: datas.u_htmc_exname,
                        value: datas.u_htmc
                    }
                },
                {
                    key: "u_zbrq",
                    value: datas.u_zbrq
                },
                {
                    key: "u_htqdsj",
                    value: datas.u_htqdrq
                },

                {
                    key: "u_gq",
                    value: datas.u_htrq
                },


                {
                    key: "u_htje",
                    value: datas.u_htje
                },

                

                {
                    key: "u_ychlrl",
                    value: datas.u_lrl
                },
                {
                    key:'u_gsglfl',
                    value:datas.u_gsglfl
                },
                {
                    key:'u_fgsglfy',
                    value:datas.u_fgsglfl
                },
                {
                    key:'u_xmms',
                    value:{
                        label:datas.xmms_name,
                        value:datas.xmms_phid
                    }
                }
            ]
            setHeadValue(arr)
            mstform.getItem("u_chzt").setValue(datas.u_chzt) // 单独是为了触发监听
            setTimeout(()=>{isTabs()},300)
        })
    }

    // 隐藏Attachment
    // 隐藏附件
    function hiddenAttmentch() {
        const u_chzt = mstform.getItem("u_chzt").getValue()
        const temp = ["u_htjdxgwj", "u_xmchxgwj", "u_swchxgwj",]
        if (!u_chzt) {
            temp.forEach(el => {
                $NG.updateUI((updater) => {
                    updater.fieldSetForm.p_form_gctzch_m[el].setProps({
                        hidden: true
                    })
                })
            })
        } else if (u_chzt == '01') {
            temp.forEach(el => {
                $NG.updateUI((updater) => {
                    updater.fieldSetForm.p_form_gctzch_m[el].setProps({
                        hidden: el == 'u_swchxgwj'
                    })
                })
            })
        } else if (u_chzt == '02') {
            temp.forEach(el => {
                $NG.updateUI((updater) => {
                    updater.fieldSetForm.p_form_gctzch_m[el].setProps({
                        hidden: el !== 'u_swchxgwj'
                    })
                })
            })
        }
    }


    // 获取版本号
    function getVersion() {
        const currentPhid = mstform.getValues().phid || '0'
        const phid = getHeadValue("u_chmc")
        $NG.execServer("SELECT", { sql: `select phid from p_form_gctzch_m where phid != ${currentPhid}` }, (res) => {
            mstform.getItem("u_bbh").setValue(res.count)
        })
    }
    // 检查是否做过收尾
    function getSwFrom() {
        const phid = getHeadValue("u_chmc")
        if (!phid) return
        $NG.execServer(`SELECT`, { sql: `select phid from p_form_gctzch_m where u_chmc = '${phid}' and u_chzt = '02'` }, (res) => {
            if (res.count != 0) {
                config.saveLock = true
                $NG.alert("当前项目策划已经含有收尾策划，不可新增！")
            } else {
                config.saveLock = false

            }
        })
    }
    // 汇总明细金额到父节点方法
    function childReduceTree(item) {
        if (Array.isArray(item)) {
            item.forEach(el => {
                if (!el.s_tree_pid || el.s_tree_pid.length < 3) {
                    const temp = childReduceTree(el)
                    el.u_bgzjje = (Number(temp.u_bgzjje) || 0)
                    el.u_syje = (Number(temp.u_syje) || 0)
                    el.u_ywgje = (Number(temp.u_ywgje) || 0)
                    el.u_yychje = (Number(temp.u_yychje) || 0)
                }
            })
            return item
        }
        let total_amt = {
            u_bgzjje: 0,
            u_syje: 0,
            u_ywgje: 0,
            u_yychje: 0,
        }
        if (item.children && item.children.length > 0) {
            item.children.forEach(el => {
                const temp = childReduceTree(el)
                el.u_bgzjje = (Number(temp.u_bgzjje) || 0)
                el.u_syje = (Number(temp.u_syje) || 0)
                el.u_ywgje = (Number(temp.u_ywgje) || 0)
                el.u_yychje = (Number(temp.u_yychje) || 0)
                total_amt.u_syje += (Number(temp.u_syje) || 0)
                total_amt.u_ywgje += (Number(temp.u_ywgje) || 0)
                total_amt.u_yychje += (Number(temp.u_yychje) || 0)
                total_amt.u_bgzjje += (Number(temp.u_bgzjje) || 0)
            })
            return total_amt
        } else {
            return {
                u_bgzjje: (Number(item.u_bgzjje) || 0),
                u_syje: (Number(item.u_syje) || 0),
                u_ywgje: (Number(item.u_ywgje) || 0),
                u_yychje: (Number(item.u_yychje) || 0)
            }
        }
    }
    // 转属性结构
    function arrayToTree(items, idField = "id", parentField = "parentId", childrenField = "children") {
        const map = {};
        const roots = [];
        ``
        // 先建立 id → item 的映射
        items.forEach(item => {
            map[item[idField]] = { ...item, [childrenField]: [] };
        });

        // 组装树
        items.forEach(item => {
            const parentId = item[parentField];
            if (parentId == null || parentId.length < 2 || parentField == '0') {
                // 根节点
                roots.push(map[item[idField]]);
            } else if (map[parentId]) {
                // 挂到父节点的 children 上
                map[parentId][childrenField].push(map[item[idField]]);
            }
        });

        return roots;
    }

    // 拆开明细不改变地址获取所有数据
    function flattenTreeAndDeduplicate(treeArr) {
        const result = []; // 新数组（地址可变，符合要求）
        const idSet = new Set(); // 记录已出现的 s_tree_id，实现去重

        // 递归遍历：直接使用原始对象，不做任何拷贝（地址完全不变）
        function traverse(node) {
            // 跳过无效节点（null/undefined/非对象）
            if (!node || typeof node !== 'object' || Array.isArray(node)) return;

            // 若 s_tree_id 未出现过，直接将原始对象加入结果数组（地址不变）
            if (!idSet.has(node.s_tree_id)) {
                idSet.add(node.s_tree_id);
                result.push(node); // 核心：直接push原始对象，引用地址完全不变
            }

            // 递归处理子节点（同样直接使用原始子对象）
            if (Array.isArray(node.children)) {
                node.children.forEach(child => traverse(child));
            }
        }

        // 遍历根节点数组（直接处理原始根对象）
        if (Array.isArray(treeArr)) {
            treeArr.forEach(rootNode => traverse(rootNode));
        }

        return result;
    }
    // 添加明细
    function parseUrlParams(url) {
        // 分离URL的哈希部分
        const hashIndex = url.indexOf('#');
        if (hashIndex === -1) return {};

        const hashPart = url.substring(hashIndex + 1);

        // 分离哈希路径和查询参数
        const questionMarkIndex = hashPart.indexOf('?');
        if (questionMarkIndex === -1) return {};

        const queryString = hashPart.substring(questionMarkIndex + 1);

        // 解析查询参数
        const params = {};
        queryString.split('&').forEach(param => {
            const [key, value] = param.split('=');
            if (key && value !== undefined) {
                params[key] = decodeURIComponent(value);
            }
        });

        return params;
    }

    // 赋值
    function setHeadValue(datas) {
        datas.forEach(item => {
            try {
                mstform.getItem(item.key).setValue(item.value)
            } catch (err) {
                console.log(`err`, err, item);
            }
        })
    }
})